import ast
import os
import json

from PIL import Image

# 配置路径和前缀 URL
folder_path = r"D:\pyimg\post\Philippines-women-20250522-resize"
url_prefix = "https://static.hitalk123.com/upload/post/p-20250527/"  # 请替换成你的线上URL路径

output_json = "D:\\pyimg\\post\\Philippines-women-post.json"
userid_json = "D:\\pyimg\\post\\user.json"

# 读取 user.json（格式为 ['123', '3445']）
try:
    with open(userid_json, "r", encoding="utf-8") as f:
        content = f.read().strip()
        user_data = ast.literal_eval(content)
except json.JSONDecodeError:
    print("错误：user.json 文件格式不正确或损坏。")
    user_data = []



# 遍历文件并生成映射
data = []
for idx, filename in enumerate(os.listdir(folder_path)):
    if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
        file_path = os.path.join(folder_path, filename)
        with Image.open(file_path) as img:
            width, height = img.size

        # 获取对应的用户信息
        if idx < len(user_data):
            userid = user_data[idx]
        else:
            userid = None

        entry = {
            "fileUrl": url_prefix + filename,
            "width": width,
            "height": height,
            "userId": userid  # 添加 userid 到 entry
        }
        data.append(entry)

# 保存为 JSON 文件
with open(output_json, "w", encoding="utf-8") as f:
    json.dump(data, f, indent=4, ensure_ascii=False)

print(f"共写入 {len(data)} 条记录到 {output_json}")
